<?php

include_once "BabiliUserSystem.php";

class BabiliUserSystemExtended extends BabiliUserSystem{
	
	/**
	 * Function that create a user in database
	 * @param $email
	 * @param $pass (password has to be encrypt)
	 * @return $userid the userid, false if failed
	*/
	public function create($email, $pass){
		
		if(empty($email) || empty($pass)){
			return false;
		}
		
		
		$query = "INSERT INTO user (email, password)
				  VALUES (:email, :password)";
		$query_args = array(':email' => $email,
							':password' => $pass
							);
		
		if($this->db->update($query, $query_args)){
			//return the id
			return $this->db->last_id();			 
		}else{
			return false;
		}
	}
	
	/**
	 * Delete an user
	 * @param $userid
	 * @return bool (true if delete, false else)
	 */
	public function delete($userid){
		
		if(empty($userid))
			return false;
		
		$query = "DELETE FROM user WHERE id = :userid";
		$query_args = array(':userid' => $userid);
		
		return $this->db->update($query, $query_args);
		
	}
	
	/**
	 * modify a user
	 * @param $userid
	 * @param $email
	 * @param $pass (already encrypted)
	 * @return bool (true if updated, false else)
	 */
	public function modify($userid, $email = null, $pass = null){
		
		if(empty($userid))
			return false;
		
		if(!empty($email) || !empty($pass)){
			$query = "UPDATE user SET ";
			$query_args = array();
			
			if(!empty($email)){
				$query .= "email = :email " ;
				$query_args[':email'] = $email;
			}
			
			if(!empty($pass)){
				$query .= "password = :password " ;
				$query_args[':password'] = $pass;
			}
			
			$query .= "WHERE id = :userid";
			$query_args[':userid'] = $userid;
			
			return $this->db->update($query, $query_args);
		}
		else{
			//Nothing to update ?
			return false;
		}
	}
	
	
	/**
	 * Log in the user
	 * @param $email
	 * @param $pass (already encrypted)
	 * @return $userid if we find it, false else
	 */
	public function login($email, $pass){
		
		if(empty($email) || empty($pass)){
			return false;
		}
		
		//test if we have an user with this email and password
		$query = "SELECT id, email FROM user WHERE email = :email AND password = :password";
		$query_args = array(':email' => $email, ':password' => $pass);
		
		$result = $this->db->select($query, $query_args);
		
		//We find a user ?
		if(!empty($result[0]['id'])){
			//Put in session
			$_SESSION['babili_user'] = $result[0];
			return $result[0]['id'];
		}
		else{
			return false;
		}
	}
}